
import UIKit
import Moya
import RxSwift

let disposeBag = DisposeBag()
class FAMUploadModel: NSObject {
    var msg:String = ""
    var code:String = "-1"
    var serverTime:Int = -1
    var url:String = ""
    var timezone:String = ""
}
class FAMUploadSourceManager: NSObject {
    @objc static let shared = FAMUploadSourceManager()
    @objc func uploadData(data:Data,block:@escaping (([String : Any]?,Error?)->Void)) -> Void {
        FAMNetHeaderConfig.shared.FAM_fillRts()
        let provider = MoyaProvider<FAMNetUploadApi>()
        provider.rx.request(.uploadData(data: data)).filterSuccessfulStatusCodes().mapJSON().subscribe { info in
            if let json = info as? [String:Any]{
                let model = FAMUploadModel()
                if let temp = json[FAM_OCString(_1997877400)] {
                    if temp is String {
                        model.code = temp as! String
                    }else if temp is NSInteger {
                        model.code = "\(temp)"
                    }
                }
                model.msg = json[FAM_OCString(_3065852031)] as? String ?? ""
                model.timezone = json[FAM_OCString(_922858135)] as? String ?? ""
                model.serverTime = json[FAM_OCString(_3154388187)] as? Int ?? 0
                if let jsonData = json[FAM_OCString(_2918445923)] {
                    guard jsonData is NSNull else {
                        let content = jsonData as! String
                        let result = FAMEncryptor.fam_AesDecrypt(content, withKey: FAMEncryptTool.aesKey(), iv: FAMEncryptTool.aesKey())
                        model.url = result
                        block(self.FAM_StringValueDic(result),nil)
                        return
                    }
                }
                block(nil,nil)
            }else {
                block(nil,nil)
            }
        } onFailure: { error in
            block(nil,error)
        }.disposed(by: disposeBag)
    }
    private func FAM_StringValueDic(_ str: String) -> [String : Any]?{
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!,
                        options: .mutableContainers) as? [String : Any] {
            return dict
        }

        return nil
    }
}
